import { getCategory1, getCategory2, getCategory3 } from "@/api/category";
import { createSlice } from "@reduxjs/toolkit";
import { message } from "antd";

// 定义state中数据的类型
interface CategoryStoreStateData {
    category1Id: number | string,
    category2Id: number | string,
    category3Id: number | string,
    categoryList1: any,
    categoryList2: any,
    categoryList3: any
}

const categorySlice = createSlice({
    name: "category",
    initialState: {
        // 一级分类列表数据
        categoryList1: [],
        category1Id: '',
        // 二级分类列表数据
        categoryList2: [],
        category2Id: '',
        // 三级分类列表数据
        categoryList3: [],
        category3Id: ''
    },
    reducers: {
        updateCategoryList1(state, { payload }) {
            state.categoryList1 = payload.data
        },
        updateCategoryList2(state, { payload }) {
            state.categoryList2 = payload.data
        },
        updateCategoryList3(state, { payload }) {
            state.categoryList3 = payload.data
        }
    }
})
const { updateCategoryList1, updateCategoryList2, updateCategoryList3 } = categorySlice.actions

// 封装发送请求的函数 在组件页面进行调用
// 获取一级分类列表
export const getCategoryList1 = () => {
    return async (dispatch: any) => {
        // 发送请求
        try {
            const res = await getCategory1()
            // console.log(res)
            dispatch(updateCategoryList1(res))
        } catch (error) {
            message.error('获取一级分类列表失败')
        }
    }
}
// 获取二级分类列表
export const getCategoryList2 = (category1Id: number) => {
    return async (dispatch: any) => {
        try {
            const res = await getCategory2(category1Id)
            dispatch(updateCategoryList2(res))
        } catch (error) {
            message.error('获取二级分类列表失败')
        }
    }
}
// 获取三级分类列表
export const getCategoryList3 = (category2Id: number) => {
    return async (dispatch: any) => {
        try {
            const res = await getCategory3(category2Id)
            dispatch(updateCategoryList3(res))
        } catch (error) {
            message.error('获取三级分类列表失败')
        }
    }
}


// export const useSelectorCategory = () => useSelector((state: any) => {
//     // console.log(state)
//     return {
//         category1Id: state.category1Id,
//         category2Id: state.category2Id,
//         category3Id: state.category3Id,
//         categoryList1: state.categoryList1,
//         categoryList2: state.categoryList2,
//         categoryList3: state.categoryList3
//     }
// })

export default categorySlice.reducer